package com.zry.android.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.Constants;
import com.zry.android.VO.UserVO;
import com.zry.android.constant.Constant;
import com.zry.android.entity.User;
import com.zry.android.service.user.IUserService;
import com.zry.android.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/api/sys")
public class LoginController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public String register(@RequestBody UserVO userVO){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickname,userVO.getAccount());

        // 判断账号是否存在
        User user = userService.getOne(queryWrapper);
        if(user != null){
            return "fail";
        }

        User newUser = new User();
        newUser.setNickname(userVO.getAccount());
        newUser.setPassword(MD5Util.md5slat(userVO.getPassword()));
        newUser.setCreateTime(new Date());
        userService.save(newUser);

        return "success";
    }

    @PostMapping("/login")
    public String login(@RequestBody UserVO userVO, HttpSession session) {

        // 判断是否登录
        User userSession = (User) session.getAttribute(Constant.SESSION_USER);
        if (userSession != null) {
            return "isLogin";
        }

        // 判断有无此用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickname, userVO.getAccount());

        User user = userService.getOne(queryWrapper);
        if(user == null){
            return "fail";
        }

        // 密码校验
        // 判断加密的密码是否与数据库中已经加密的密码一致
        String password = MD5Util.md5slat(userVO.getPassword());
        if(!password.equals(user.getPassword())){
            return "InvalidPassword";
        }


        // 验证机校验
        String code = userVO.getCode();
        String sessionCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (code.equalsIgnoreCase(sessionCode)) {
            session.setAttribute(Constant.SESSION_USER, user);
            return "InvalidCode";
        }

        return "success";
    }

    @PostMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "success";
    }

}
